package simpleTaskBoard.business;

import java.util.ArrayList;
import java.util.List;

import ch.ivyteam.ivy.environment.Ivy;

import simpleTaskBoard.dao.TaskDAO;
import simpleTaskBoard.dto.TaskDTO;
import simpleTaskBoard.entities.TaskEntity;

public class TaskBusiness {
	
	private static final int MAX_TASK = 5;
	TaskDAO dao = new TaskDAO();
	
	public TaskBusiness(){
		
	};
	
	public void saveTask(TaskDTO task){
		dao.addTask(task.convertToEntity(task));
	}
	
	public void updateTask(TaskDTO task){		
		TaskDTO oldTask= getByID(task.getId());
		if(!"".equals(task.getAssigned())) {
			assertUserAssignedToOverMaxTask(task.getAssigned());
		}
		HistoryBusiness hisBus = new HistoryBusiness();
		hisBus.setChangeHistory(task, oldTask);
		dao.updateTask(task.convertToEntity(task));
	}
	
	public List<TaskDTO> getAll(){
		List<TaskDTO> listTask = new ArrayList<TaskDTO>();
		List<TaskEntity> listTaskDao = dao.getAll();
		for(TaskEntity t : listTaskDao){
			listTask.add(new TaskDTO(t));
		}
		return listTask;
	}
	
	public TaskDTO getByID(long id){
		TaskEntity TaskDao = dao.getByID(id);
		return new TaskDTO(TaskDao);
	}
	
	public void assertUserAssignedToOverMaxTask(String userName) {
		if(isAssignedOverMaxTask(userName)) {
			throw new IllegalStateException("The user already taken maximum tasks !");
		}
	}
	
	public boolean isAssignedOverMaxTask(String userName) {
		List<TaskEntity> listTaskEntity = dao.findAllTaskAssignedToUser(userName);
		if(MAX_TASK <= listTaskEntity.size()) {
			return true;
		}
		return false;
	}
}
